﻿using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using YAXLib;

namespace RaytracerLib.Script
{
    public class ScriptParams : IEnumerable<ScriptParam>
    {
        [YAXCollection(SerializationType =
            YAXCollectionSerializationTypes.InnerCollectionRecursiveInElement)]
        private List<ScriptParam> m_params = new List<ScriptParam>();

        public ScriptParams(object a_script)
        {
            var paramss = from field in a_script.GetType().GetFields()
                          where field.GetCustomAttributes(true).Any(t =>
                                    t is ScriptParamAttribute)
                          select new
                          {
                              Field = field,
                              Name = (field.GetCustomAttributes(true).First(t =>
                                        t is ScriptParamAttribute) as
                                        ScriptParamAttribute).Name ?? field.Name
                          };

            foreach (var param in paramss)
            {
                Debug.Assert(this.All(p => p.Name != param.Name));

                m_params.Add(new ScriptParam(param.Name, a_script, param.Field));
            }
        }

        public void Inject(ScriptParams a_params)
        {
            foreach (var param in a_params)
                this[param.Name].Value = param.Value;
        }

        public ScriptParam this[string a_name]
        {
            get
            {
                return m_params.First(p => p.Name == a_name);
            }
        }

        public IEnumerator<ScriptParam> GetEnumerator()
        {
            return m_params.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return m_params.GetEnumerator();
        }
    }
}